pub struct UrlPared {
    pub base_url: String,
    pub params: Vec<String>,
}

impl UrlPared {
    pub fn init(url_str: &str) -> Result<Self, url::ParseError> {
        let url_info = url::Url::parse(url_str)?;
        let base_url = format!(
            "{}://{}{}",
            url_info.scheme(),
            url_info.host_str().unwrap_or(""),
            url_info.path()
        );
        let params = url_info
            .query_pairs()
            .map(|(k, v)| format!("\"{}\": \"{}\"", k, escape_string(&v)))
            .collect::<Vec<String>>();
        Ok(Self { base_url, params })
    }
    pub fn to_python(&self) -> String {
        let mut code = String::new();
        code.push_str(&format!("url = \"{}\"\n", self.base_url));

        if !self.params.is_empty() {
            code.push_str("params = {\n");
            for p in &self.params {
                code.push_str(&format!("    {},\n", p));
            }
            code.push_str("    }\n");
        }

        code
    }
    pub fn to_rust(&self) -> String {
        let mut code = String::new();
        code.push_str(&format!("let url = \"{}\";\n", self.base_url));

        if !self.params.is_empty() {
            code.push_str("    let params =hashmap! { \n");
            for p in &self.params {
                code.push_str(&format!("        {},\n", p.replace(":", "=>")));
            }
            code.push_str("    };\n");
        }

        code
    }
}

fn escape_string(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('\"', "\\\"")
        .replace('\n', "\\n")
        .replace('\t', "\\t")
        .replace('\r', "\\r")
}
